package com.ruike.alisurface.ui.settings;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CalendarView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.hjq.xtoast.XToast;
import com.ruike.alisurface.R;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.EditSlotPositionBean;
import com.ruike.alisurface.bean.ProductListBean;
import com.ruike.alisurface.bean.PupBean;
import com.ruike.alisurface.bean.SlotDetailsBean;
import com.ruike.alisurface.bean.SlotLocationBean;
import com.ruike.alisurface.bean.replenBean;
import com.ruike.alisurface.https.SettingHttp;
import com.ruike.alisurface.serialport.MsgEventBus;
import com.ruike.alisurface.ui.adapters.LocalReplenAdapter;
import com.ruike.alisurface.ui.adapters.ReplenAdapter;
import com.ruike.alisurface.utils.GsonUtils;
import com.ruike.alisurface.utils.LinearItemDecoration;
import com.ruike.alisurface.utils.PopupWindowUtil;
import com.ruike.alisurface.utils.PxUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.BezierRadarHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.voodoo.lib_http.ApiListener;
import com.voodoo.lib_logcat.L;
import com.voodoo.lib_utils.SharedUtils;
import com.voodoo.lib_utils.imageLoader.GlideImageLoader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;


public class ReplenishmentMag_Aty extends BaseAty implements ApiListener {
    @BindView(R.id.to_back)
    ImageView toBack;
    @BindView(R.id.replemag_one_click_replenishment)
    TextView one_click_replenishment;
    @BindView(R.id.slot_list_rv)
    RecyclerView slotListRv;

    @Override
    protected int getLayoutResId() {
        return R.layout.app_replenishment_management;
    }

    @Override
    protected void initViews() {
        initTitleBar(false);
        toBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        one_click_replenishment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showProgressDialog("一键补货中，请等待");
                SettingHttp.mch_one_key_replenishment(ReplenishmentMag_Aty.this);
            }
        });
    }

    List<replenBean.RowsBean> replenList = new ArrayList<>();
    ReplenAdapter replenAdapter;
    RefreshLayout refreshLayout;

    @Override
    protected void initData() {


        replenAdapter = new ReplenAdapter(replenList, this);
        slotListRv.setLayoutManager(new LinearLayoutManager(this));
        slotListRv.setAdapter(replenAdapter);
        replenAdapter.setEmptyView(R.layout.item_emptyview);
//        replenAdapter.setFooterView();
        loadMore();

        //https://github.com/scwang90/SmartRefreshLayout
        refreshLayout = (RefreshLayout) findViewById(R.id.refreshlayout);
        //设置 Header 为 贝塞尔雷达 样式
        refreshLayout.setRefreshHeader(new BezierRadarHeader(this).setEnableHorizontalDrag(true));
//        //设置 Footer 为 球脉冲 样式
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                pageTotal = 10;
                loadMore();
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMore();
                refreshLayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });

        replenAdapter.addChildClickViewIds(R.id.replen_replenishment, R.id.replen_edit);
        replenAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                switch (view.getId()) {
                    case R.id.replen_replenishment:
                        if (isSueess) {
                            L.i("点击了补货  isSueess==");
                            return;
                        }
                        isSueess = true;
                        slot_type = 2;
                        L.i("点击了补货  position==" + position);
                        if (mReplenishmentxToast != null && mReplenishmentxToast.isShow()) {
                            L.i("xToast=补货框已经弹出");
                            return;
                        }
                        showSlotDetails(position);
                        break;

                    case R.id.replen_edit:
                        if (isSueess) {
                            L.i("点击了编辑  isSueess==");
                            return;
                        }
                        isSueess = true;
                        slot_type = 1;
                        if (mEditxToast != null && mEditxToast.isShow()) {
                            L.i("xToast=编辑弹框已经弹出");
                            return;
                        }
                        L.i("点击了编辑position==" + position);
                        showSlotDetails(position);
                        break;

                    default:
                        break;
                }
            }
        });
    }

    boolean isSueess;
    int slot_type = 0;
    int index;

    public void showSlotDetails(int position) {
        showProgressDialog("正在加载数据中，请等待...");
        SettingHttp.get_slot_position_detail(replenList.get(position).getId(), slot_type, this);
    }

    int page = 1;
    int pageTotal = 10;

    private void loadMore() {
        SettingHttp.get_mch_slot_setting_list(page, pageTotal, this);
    }

    @Override
    public void onEventBusResult(MsgEventBus event) {
        super.onEventBusResult(event);
        if (event.getType().equals("货道更新")) {
            showProgressDialog("正在请求数据中，请等待...");
            page = 1;
            refreshLayout.autoRefresh();
        }
    }

    @Override
    public void onRequestStart(String requestUrl, int requestId) {

    }

    @Override
    public void onRequestComplete(String requestUrl, int requestId) {
        removeProgressDialog();

    }

    @Override
    public void onSuccess(String requestUrl, JSONObject requestJson, int requestId) {
        if (requestUrl.endsWith(SettingHttp.mch_one_key_replenishment)) {
            L.i("onSuccess=");
            SettingHttp.get_mch_slot_setting_list(1, 10, this);
        }
        if (requestUrl.endsWith(SettingHttp.get_mch_slot_setting_list)) {
            L.i("onSuccess=");
            replenBean replenBean = GsonUtils.fromJson(requestJson.toString(), replenBean.class);
            if (replenBean.getRows().size() <= 0) {
                refreshLayout.setNoMoreData(true);
                if (page == 1) {
                    replenAdapter.notifyDataSetChanged();
                }
                return;
            }
            page++;
            replenList.clear();
            replenList.addAll(replenBean.getRows());
            replenAdapter.notifyDataSetChanged();
            return;
        }

        if (requestUrl.endsWith(SettingHttp.get_slot_position_detail)) {
            L.i("onSuccess=");
            if (slot_type == 1) {
                SlotDetailsBean slotDetailsBean = GsonUtils.fromJson(requestJson.toString(), SlotDetailsBean.class);
                slotDetail = slotDetailsBean.getData();

                showEditDialog();
            } else {
                SlotLocationBean slotLocationBean = GsonUtils.fromJson(requestJson.toString(), SlotLocationBean.class);
                slotdata.clear();
                index = slotLocationBean.getData().getIndex();
                slotdata.addAll(slotLocationBean.getData().getSlot_pos());
                Collections.reverse(slotdata);
                showReplenishmentDialog();
            }

            return;
        }

        if (requestUrl.endsWith(SettingHttp.get_slot_product_list)) {
            L.i("onSuccess=");
            ProductListBean productListBean = GsonUtils.fromJson(requestJson.toString(), ProductListBean.class);
            dataBeanList.clear();
            dataBeanList.addAll(productListBean.getData());
            pupProductnameList(product_name);
        }
        if (requestUrl.endsWith(SettingHttp.edit_slot_position)) {
            L.i("onSuccess=");
            cancelmReplenishmentxToast();
        }
        if (requestUrl.endsWith(SettingHttp.edit_slot)) {
            L.i("onSuccess=");
            cancelmEditxToast();
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg, String resultData, int requestId) {
        if (requestUrl.endsWith(SettingHttp.mch_one_key_replenishment)) {
            L.i("onError==" + errorMsg);
            showErrorToast(errorMsg);
        }
        if (requestUrl.endsWith(SettingHttp.get_mch_slot_setting_list)) {
// 当前这次数据加载错误，调用此方法
            L.i("onError=" + errorMsg);
        }

        if (requestUrl.endsWith(SettingHttp.get_slot_position_detail)) {
            L.i("onError=" + errorMsg);
            showErrorToast(errorMsg);
            isSueess = false;
        }
        if (requestUrl.endsWith(SettingHttp.edit_slot_position)) {
            L.i("onError=" + errorMsg);
            showErrorToast(errorMsg);
        }
        if (requestUrl.endsWith(SettingHttp.edit_slot)) {
            L.i("onError=" + errorMsg);
            showErrorToast(errorMsg);
        }
    }


    /**
     * xToast 的创建
     *
     * @param width
     * @param heigh
     * @return
     */
    private void showXToast(int width, int heigh, XToast xToast) {
        xToast.setAnimStyle(android.R.style.Animation_Toast);
        xToast.setBackgroundDimAmount(0.6f);
        xToast.setWidth(PxUtils.dp2px(this, width));
        xToast.setHeight(PxUtils.dp2px(this, heigh));
        xToast.setYOffset(PxUtils.dp2px(this, 420));
        xToast.setGravity(Gravity.TOP | Gravity.CENTER_VERTICAL);
        xToast.setOutsideTouchable(false);
    }

    List<SlotLocationBean.DataBean.SlotPosBean> slotdata = new ArrayList<>();
    XToast mReplenishmentxToast;
    LocalReplenAdapter localReplenAdapter;

    /**
     * 补货弹框
     */
    public void showReplenishmentDialog() {

        View toastView = LayoutInflater.from(this).inflate(R.layout.dialog_replenishment, null);
        mReplenishmentxToast = new XToast(this).setView(toastView);
        showXToast(1060, 900, mReplenishmentxToast);
        mReplenishmentxToast.show();
        L.i("==   创建补货弹框 =" + mReplenishmentxToast);
        RecyclerView recyclerView = toastView.findViewById(R.id.dialog_replen_rv);
        LinearItemDecoration divider = new LinearItemDecoration.Builder(this)
                .setSpan(10f)
                .setColorResource(R.color.color_white)
                .setShowLastLine(true)
                .build();
        recyclerView.addItemDecoration(divider);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        TextView save_changes = toastView.findViewById(R.id.dialog_save_changes_tv);
        localReplenAdapter = new LocalReplenAdapter(slotdata, this);

        recyclerView.setAdapter(localReplenAdapter);

        localReplenAdapter.addChildClickViewIds(R.id.item_move_up, R.id.item_move_down, R.id.item_status, R.id.item_valid_period, R.id.item_del_period);
        localReplenAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                KeyboardUtils.hideSoftInput(view);
                cancelmCalendar();
                TextView item_valid_period = view.findViewById(R.id.item_valid_period);
                switch (view.getId()) {
                    case R.id.item_status:

                        L.i("货道位置状态=" + position);
                        TextView item_status = view.findViewById(R.id.item_status);
                        pupSlotLocationStatus(item_status, position);
                        break;

                    case R.id.item_valid_period:
                        L.i("有效期=" + position);
                        if (mCalendarxToast != null && mCalendarxToast.isShow()) {
                            L.i("xToast=日历弹框已经弹出");
                            return;
                        }
                        showCalendarView(item_valid_period, position);
                        break;
                    case R.id.item_move_up:
                        L.i("上移动=" + position);
                        setMove(position, 0);
                        localReplenAdapter.notifyDataSetChanged();

                        L.i("上移动=====");
                        break;
                    case R.id.item_move_down:
                        L.i("下移动=" + position);
                        setMove(position, 1);

                        localReplenAdapter.notifyDataSetChanged();


                        break;
                    case R.id.item_del_period:
                        L.i("删除日期=====");

                        slotdata.get(position).setWarranty_time_format("");
                        slotdata.get(position).setWarranty_time("");
                        localReplenAdapter.notifyDataSetChanged();
                        break;

                }
            }
        });
        save_changes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                L.i("=保存位置信息=");
                KeyboardUtils.hideSoftInput(view);
                sendSlotPosnitioninfo();
            }
        });
        TextView dialog_cancel = toastView.findViewById(R.id.dialog_cancel);
        dialog_cancel.setOnClickListener(v -> {
            L.i("==点击了货道补货取消=");
            KeyboardUtils.hideSoftInput(v);
            cancelmReplenishmentxToast();

        });

    }


    boolean issave = false;

    public void sendSlotPosnitioninfo() {
        issave = false;
        for (int i = 0; i < slotdata.size(); i++) {
            if (1 == slotdata.get(i).getPosition_state()) {
                issave = true;
            } else if (issave) {
                issave = false;
                showErrorToast("不可隔着摆放商品");
                return;
            }
        }

        showProgressDialog("正在修改数据中，请等待...");
        EditSlotPositionBean editSlotPositionBean = new EditSlotPositionBean();
        List<Integer> indexs = new ArrayList<>();
        indexs.add(index);
        editSlotPositionBean.setIndexs(indexs);
        editSlotPositionBean.setMch_id(SharedUtils.getInstance().getString(ShareKey.MCH_ID));
        editSlotPositionBean.setSlot_pos(slotdata);
        String json = GsonUtils.toJson(editSlotPositionBean);
        SettingHttp.edit_slot_position(json, this);
    }


    /**
     * @param position 要移动的数据 的下标
     * @param type     0 上移  还是  1 下移
     */
    public void setMove(int position, int type) {
        if (slotdata.size() < 2) {
            return;
        }
        SlotLocationBean.DataBean.SlotPosBean slotPosCurrent = GsonUtils.fromJson(
                GsonUtils.toJson(slotdata.get(position)), SlotLocationBean.DataBean.SlotPosBean.class);
        int moveposition;
        if (type == 0) {
            moveposition = position - 1;
        } else {

            moveposition = position + 1;
        }
        SlotLocationBean.DataBean.SlotPosBean slotPosMove = GsonUtils.fromJson(
                GsonUtils.toJson(slotdata.get(moveposition)), SlotLocationBean.DataBean.SlotPosBean.class);
        MoveData(moveposition, slotPosCurrent);
        MoveData(position, slotPosMove);

    }

    public void MoveData(int position, SlotLocationBean.DataBean.SlotPosBean posBean) {
        slotdata.get(position).setPosition_state(posBean.getPosition_state());
        slotdata.get(position).setBatch_no(posBean.getBatch_no());
        slotdata.get(position).setSter_no(posBean.getSter_no());
        slotdata.get(position).setWarranty_time_format(posBean.getWarranty_time_format());
        slotdata.get(position).setWarranty_time(posBean.getWarranty_time());
    }

    SlotDetailsBean.DataBean slotDetail;
    EditText product_name;
    EditText price, maxstock, warningtock, currentstock;
    ImageView slot_img, search_img;

    XToast mEditxToast;

    /**
     * 编辑弹框
     */
    public void showEditDialog() {
        View toastView = LayoutInflater.from(this).inflate(R.layout.dialog_commodity_editor, null);
        mEditxToast = new XToast(this).setView(toastView);
        showXToast(1060, 540, mEditxToast);
        mEditxToast.show();
        L.i("==   创建编辑弹框 =" + mEditxToast);
        TextView save_changes = toastView.findViewById(R.id.dialog_save_changes_tv);
        TextView index = toastView.findViewById(R.id.slot_edit_index);
        TextView status = toastView.findViewById(R.id.slot_edit_status);
        TextView type = toastView.findViewById(R.id.slot_edit_type);
        product_name = toastView.findViewById(R.id.slot_edit_name);
        search_img = toastView.findViewById(R.id.search_img);
        price = toastView.findViewById(R.id.slot_edit_price);
        maxstock = toastView.findViewById(R.id.slot_edit_maxstock);
        warningtock = toastView.findViewById(R.id.slot_edit_warningtock);
        currentstock = toastView.findViewById(R.id.slot_edit_currentstock);
        slot_img = toastView.findViewById(R.id.slot_edit_img);

        if (slotDetail != null) {
            index.setText(slotDetail.getIndex() + "");
            status.setText(slotDetail.getSlot_state_id_str());
            type.setText(slotDetail.getSlot_type_id_str());
            maxstock.setText(slotDetail.getMaxcount() + "");
            currentstock.setText(slotDetail.getCount() + "");
            warningtock.setText(slotDetail.getShortageThreshold() + "");
            setProductdetails();
        }

        save_changes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                L.i("=保存货道商品信息=");
                KeyboardUtils.hideSoftInput(view);
                if (TextUtils.isEmpty(maxstock.getText().toString())) {
                    showErrorToast("最大库存不能为空");
                    return;
                }
                int maxCount = Integer.parseInt(maxstock.getText().toString());
                if (maxCount <= 0) {
                    showErrorToast("最大库存不能为零");
                    return;
                }
                if (TextUtils.isEmpty(currentstock.getText().toString())) {
                    showErrorToast("当前库存不能为空");
                    return;
                }
                int curCount = Integer.parseInt(currentstock.getText().toString());
                if (curCount > maxCount) {
                    showErrorToast("当前库存不能大于最大库存");
                    return;
                }
                sendSlotinfo();
            }
        });
        TextView dialog_cancel = toastView.findViewById(R.id.dialog_cancel);
        dialog_cancel.setOnClickListener(new View.OnClickListener() {
                                             @Override
                                             public void onClick(View v) {
                                                 L.i("==点击了货道编辑取消=");
                                                 cancelmEditxToast();
                                             }
                                         }
        );
        status.setOnClickListener(view -> {
            KeyboardUtils.hideSoftInput(view);
            pupSlotStatus(status);

        });
        type.setOnClickListener(view -> {
            KeyboardUtils.hideSoftInput(view);
            pupSlotType(type);


        });
        search_img.setOnClickListener(view -> {
            KeyboardUtils.hideSoftInput(view);
            if (popupWindowUtil != null && popupWindowUtil.isShowing()) {
                L.i("已经弹出了");
                return;
            }
            showProgressDialog("正在加载商品中，请等待...");
            SettingHttp.get_slot_product_list(this);

        });
    }


    public void sendSlotinfo() {
        showProgressDialog("正在修改数据中，请等待...");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("mch_id", SharedUtils.getInstance().getString(ShareKey.MCH_ID));
            JSONArray jsonArray = new JSONArray();
            jsonArray.put(slotDetail.getIndex());
            jsonObject.put("indexs", jsonArray);
            jsonObject.put("product_id", slotDetail.getProductid());
            jsonObject.put("set_price", price.getText().toString());
            jsonObject.put("slot_state", slotDetail.getSlotStateId());
            jsonObject.put("slot_type", slotDetail.getSlotTypeId());
            jsonObject.put("max_count", maxstock.getText().toString());
            jsonObject.put("now_count", currentstock.getText().toString());
            jsonObject.put("shortageThreshold", warningtock.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        SettingHttp.edit_slot(jsonObject.toString(), this);
    }


    XToast mCalendarxToast;

    /**
     * 日历弹框
     */
    public void showCalendarView(TextView item_valid_period, int position) {
        View toastView = LayoutInflater.from(this).inflate(R.layout.dialog_calendview, null);
        mCalendarxToast = new XToast(this).setView(toastView).setAnimStyle(android.R.style.Animation_Toast);
        mCalendarxToast.setWidth(1060);
        mCalendarxToast.setHeight(420);
        mCalendarxToast.setOutsideTouchable(false);
        mCalendarxToast.setGravity(Gravity.TOP | Gravity.CENTER_VERTICAL);
        CalendarView item_calendar = toastView.findViewById(R.id.item_calendar);

        ImageView dialog_cancel = toastView.findViewById(R.id.dialog_cancel);
        dialog_cancel.setOnClickListener(view -> cancelmCalendar());
        item_calendar.setOnDateChangeListener((calendarView, year, month, day) -> {
            L.i("=日期信息=" + year + "_" + month + 1 + "_" + day);
            String monthstr;
            if (month + 1 > 9) {
                monthstr = String.valueOf(month + 1);
            } else {
                monthstr = "0" + String.valueOf(month + 1);
            }
            String daystr;
            if (day > 9) {
                daystr = String.valueOf(day);
            } else {
                daystr = "0" + String.valueOf(day);
            }
            String time = year + "-" + monthstr + "-" + daystr;
            slotdata.get(position).setWarranty_time_format(time);
            slotdata.get(position).setWarranty_time(time);
            localReplenAdapter.notifyDataSetChanged();
            cancelmCalendar();
        });
        mCalendarxToast.show();
    }

    /**
     * 货道状态
     */
    public void pupSlotStatus(TextView item_str) {
        List<PupBean> pupBeanList = new ArrayList<>();
        PupBean pupBean1 = new PupBean("可用", "22001");
        PupBean pupBean2 = new PupBean("停用", "22002");
        PupBean pupBean3 = new PupBean("故障", "22003");
        pupBeanList.add(pupBean1);
        pupBeanList.add(pupBean2);
        pupBeanList.add(pupBean3);

        PopupWindowUtil popupWindowUtil = new PopupWindowUtil(this, pupBeanList);

        popupWindowUtil.setItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                item_str.setText(pupBeanList.get(i).getTitle());
                slotDetail.setSlotStateId(Integer.parseInt(pupBeanList.get(i).getTitle_id()));
                popupWindowUtil.dismiss();
            }
        });
        popupWindowUtil.show(item_str, pupBeanList.size());
    }

    /**
     * 货道类型
     */
    public void pupSlotType(TextView item_str) {
        List<PupBean> pupBeanList = new ArrayList<>();
        PupBean pupBean1 = new PupBean("弹簧货道", "21001");
        PupBean pupBean2 = new PupBean("履带", "21002");
        PupBean pupBean3 = new PupBean("电磁锁", "21003");
        pupBeanList.add(pupBean1);
        pupBeanList.add(pupBean2);
        pupBeanList.add(pupBean3);
        PopupWindowUtil popupWindowUtil = new PopupWindowUtil(this, pupBeanList);

        popupWindowUtil.setItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                item_str.setText(pupBeanList.get(i).getTitle());
                slotDetail.setSlotTypeId(Integer.parseInt(pupBeanList.get(i).getTitle_id()));
                popupWindowUtil.dismiss();
            }
        });

        popupWindowUtil.show(item_str, pupBeanList.size());
    }


    /**
     * 货道位置状态
     */
    public void pupSlotLocationStatus(TextView item_str, int position) {
        List<PupBean> pupBeanList = new ArrayList<>();
        PupBean pupBean1 = new PupBean("缺货", "0");
        PupBean pupBean2 = new PupBean("有货", "1");
        pupBeanList.add(pupBean1);
        pupBeanList.add(pupBean2);

        PopupWindowUtil popupWindowUtil = new PopupWindowUtil(this, pupBeanList);

        popupWindowUtil.setItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                item_str.setText(pupBeanList.get(i).getTitle());
                slotdata.get(position).setPosition_state(Integer.parseInt(pupBeanList.get(i).getTitle_id()));
                popupWindowUtil.dismiss();
            }
        });
        popupWindowUtil.setOff(0, 1);
        popupWindowUtil.show(item_str, pupBeanList.size());
    }

    List<ProductListBean.DataBean> dataBeanList = new ArrayList<>();
    PopupWindowUtil popupWindowUtil;

    /**
     * 货道商品集合
     */
    public void pupProductnameList(TextView item_str) {
        List<PupBean> pupBeanList = new ArrayList<>();
        if (!TextUtils.isEmpty(item_str.getText().toString())) {
            for (ProductListBean.DataBean dataBean : dataBeanList) {
                if (dataBean.getProduct_name().contains(item_str.getText().toString())) {
                    PupBean pupBean1 = new PupBean(dataBean.getProduct_name(), dataBean.getProduct_id());
                    pupBeanList.add(pupBean1);
                }
            }
        } else {
            for (ProductListBean.DataBean dataBean : dataBeanList) {
                PupBean pupBean1 = new PupBean(dataBean.getProduct_name(), dataBean.getProduct_id());
                pupBeanList.add(pupBean1);
            }
        }
        popupWindowUtil = new PopupWindowUtil(this, pupBeanList);
        popupWindowUtil.setItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                for (ProductListBean.DataBean dataBean : dataBeanList) {
                    if (dataBean.getProduct_id().equals(pupBeanList.get(i).getTitle_id())) {
                        slotDetail.setProductname(dataBean.getProduct_name());
                        slotDetail.setProductid(dataBean.getProduct_id());
                        slotDetail.setPrice(Double.parseDouble(dataBean.getPrice()));
                        slotDetail.setProductimg(dataBean.getImg());
                        setProductdetails();
                    }
                }

                popupWindowUtil.dismiss();
            }
        });
        popupWindowUtil.setOff(0, 1);
        popupWindowUtil.show(item_str, pupBeanList.size());
    }

    public void setProductdetails() {
        if (slotDetail != null) {
            product_name.setText(slotDetail.getProductname() + "");
            price.setText(slotDetail.getPrice() + "");
            GlideImageLoader.getInstance().loadImage(this, slotDetail.getProductimg(), slot_img);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelmCalendar();
        cancelmReplenishmentxToast();
        cancelmEditxToast();
        if (popupWindowUtil != null) {
            popupWindowUtil.dismiss();
            popupWindowUtil = null;
        }
    }

    public void cancelmCalendar() {
        L.i("==  取消日历弹框 =" + mCalendarxToast);
        if (mCalendarxToast != null) {
            mCalendarxToast.cancel();
            mCalendarxToast = null;
        }
    }

    public void cancelmReplenishmentxToast() {
        isSueess = false;
        L.i("==  取消补货弹框 =" + mReplenishmentxToast);
        if (mReplenishmentxToast != null) {
            mReplenishmentxToast.cancel();
            mReplenishmentxToast = null;
        }
    }

    public void cancelmEditxToast() {
        isSueess = false;
        L.i("==  取消货道编辑弹框 =" + mEditxToast);
        if (mEditxToast != null) {
            mEditxToast.cancel();
            mEditxToast = null;
        }
    }
}
